import { Component, OnInit, OnChanges, Input, ElementRef, SimpleChanges } from '@angular/core';

import * as echarts from 'echarts';

interface chartConfigs {
  legendData: Array<string>,
  xAxisData: Array<any>,
  seriesData: Array<any>
}

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.scss']
})
export class LineChartComponent implements OnInit, OnChanges {
  @Input() idNum: number = 1;
  @Input() chartHeight: string = '400px';
  @Input() chartConfig: chartConfigs = {
    legendData: [],
    xAxisData: [],
    seriesData: []
  };

  constructor(
    private el: ElementRef,
  ) { }

  ngOnInit(): void {
  }

  ngOnChanges(changes: SimpleChanges): void {
    // setTimeout(() => {
    //   this.initCharts();
    // }, 100)
  }

  initCharts() {
    let domId = '#chart' + this.idNum;
    let chartDom: any = this.el.nativeElement.querySelector(domId);
    let myChart = echarts.init(chartDom);

    let option;
    option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        type: 'scroll',
        data: this.chartConfig.legendData
      },
      grid: {
        left: '3.5%',
        right: '3%',
        bottom: '6.5%',
        containLabel: false
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: this.chartConfig.xAxisData
      },
      yAxis: {
        type: 'value'
      },
      series: this.chartConfig.seriesData
    };

    option && myChart.setOption(option);

    window.addEventListener('resize', () => {
      myChart.resize();
    })
  }
}
